import Vue from 'vue';
import Router from 'vue-router';
import store from '../store/index'
import Layout from '../views/layout/Layout.vue';

Vue.use(Router);

// 假设你已经在某个地方设置了 window.isLoggedIn = true 或 false

export const constantRouterMap = [
  { path: '/', component: () => import('../views/login/index.vue'), hidden: true }, // 更改为/login路径
  { path: '/404', component: () => import('../views/404.vue'), hidden: true },

  {
    path: '/home',
    component: Layout,
    redirect: '/home/page1', // 更改为你希望默认跳转的具体子路由
    meta: { title: '员工管理', icon: 'home' },
    children: [
      {
        path: 'page1',
        name: 'page1',
        component: () => import('@/views/page1/index'),
        meta: { title: 'welink管理', icon: 'ums-admin', requiresAuth: true } // 添加requiresAuth标识
      },
      {
        path: 'page2',
        name: 'page2',
        component: () => import('@/views/page2/index'),
        meta: { title: '精益考勤', icon: 'dashboard', requiresAuth: true }
      },
      {
        path: 'page3',
        name: 'page3',
        component: () => import('@/views/page3/index'),
        meta: { title: '明细考勤', icon: 'video', requiresAuth: true }
      },
      {
        path: 'page4',
        name: 'page4',
        component: () => import('@/views/page4/index'),
        meta: { title: '文件上传', icon: 'video', requiresAuth: true }
      },
      {
        path: 'page5',
        name: 'page5',
        component: () => import('@/views/page5/index'),
        meta: { title: '批量demo', icon: 'video', requiresAuth: true }
      },
    ]
  },
  // 如果所有未匹配到的路由都应重定向到404页面，可以添加如下：
  { path: '*', redirect: '/404', hidden: true }
];

const createRouter = () => new Router({
  mode: 'history',
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
});

const router = createRouter();

export function resetRouter() {
  const newRouter = createRouter();
  router.matcher = newRouter.matcher; // 重置路由器
}

router.beforeEach((to, from, next) => {
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  console.log("当前状态", store.getters.isLoggedIn);
  // 使用全局变量 window.isLoggedIn 来判断用户是否已登录
  if (requiresAuth && !store.getters.isLoggedIn) {
    // 如果需要登录且未登录，则跳转到登录页
    next({
      path: '/', // 使用/login而非/
      query: { redirect: to.fullPath } // 将尝试访问的路径作为查询参数传递给登录页
    });
  } else {
    next(); // 确保调用next()，否则导航将被挂起
  }
});

export default router;